package com.travel.carmen;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


/**
	Login functionality for the Travel Mobile Application Carmen.
	 The View is the Login Interface (layout as per login.xml) for the application.
	 Purpose is to connect to the Drupal website for Carmen. That is,
	 users can log into Carmen accounts.
   	@author Arturo Aparicio 
   	@author Edwin Boykin 
   	@author Veena Chengalnaidu
   	@author Anton Ganeshalingam
   	@author Lakshmi Mallampati
   	@author Tarun Morton
   	@author Chantha Thoeun
*/
public class Login extends Activity
{
	// Identifiers
	private static final int ZERO = 0;
    
	// ProgressDialog
	private ProgressDialog dialog;
	
	// Layout
	private EditText usernameEditText;
	private EditText passwordEditText;
	private TextView notRegisteredTextView;
	private TextView forgotPasswordTextView;
	private Button signinButton;
	
	// Member variables
	private String username;
	private String password;
	private boolean connected = false;
	private boolean isValidAccount = false;
	
	@Override
	/**
	   Called when the activity is first created.
	    The UI activities as per login.xml are inflated.
	    All listeners and adapters are attached and all settings are
	    made to default.
	 */
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.login);
		setupForDrupalAccess();
		
		usernameEditText = (EditText) findViewById(R.id.UsernameEditText);
		passwordEditText = (EditText) findViewById(R.id.PasswordEditText);
		
		notRegisteredTextView  = (TextView) findViewById(R.id.not_registered);
		forgotPasswordTextView = (TextView) findViewById(R.id.forgot_password);
		
		notRegisteredTextView.setOnClickListener(connectToBrowserListener);
		forgotPasswordTextView.setOnClickListener(connectToBrowserListener);
		
		signinButton     = (Button) findViewById(R.id.sign_in_button);
		signinButton.setOnClickListener(signInListener);
		
		dialog = new ProgressDialog(this);
		dialog.setMessage("Logging into Carmen...");
		dialog.setIndeterminate(true);
	}
	
	
	/**
	   Initialize Carmen with shared preferences for making XML-RPC requests.
	 */
	private void setupForDrupalAccess() 
	{
		SharedPreferences settings;
		settings = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("apiKey", getString(R.string.apikey));
		editor.putString("serviceDomain", getString(R.string.domain));
		editor.putString("serviceURL", getString(R.string.url));
		editor.commit();
	}
	
	
	/** 
	 	Listener for hyperlinks (Non-registered users and Forgotten passwords 
		 for registered users. A browser intent is launched with the
		 appropriate link to the Carmen (Drupal) website.
	 */
	private OnClickListener connectToBrowserListener = new OnClickListener() 
	{
		@Override
		public void onClick(View v) 
		{
			if (v.getId() == R.id.not_registered)
			{
				Intent nr = new Intent("android.intent.action.VIEW",
						Uri.parse(getString(R.string.register)));
				startActivity(nr);
			}
			
			if (v.getId() == R.id.forgot_password)
			{
				Intent fp = new Intent("android.intent.action.VIEW",
						Uri.parse(getString(R.string.forgot)));
				startActivity(fp);
			}
		}
	};
	
	
	/** 
	 	Listener for Sign in for Carmen registered users. Proceeds
	 	 only on sufficient login in provided by users. That is,
	 	 a username and password must be entered for verification. 
	 */
	private OnClickListener signInListener = new OnClickListener() 
	{
		@Override
		public void onClick(View v) 
		{
			boolean loginValid = isValidLogin();
			
			if (loginValid)
			{
				dialog.show();
				Thread thread = new Thread() 
				{
					@Override
					public void run() 
					{
						connected = connectToDrupal();
						handler.sendEmptyMessage(ZERO);
					}
				};
                thread.start();
			}
		}
	};
	
	
	/** 
	 	Handler for cases related to logging into Carmen website.
	 	 If the website is under maintenance, a message will prompt
	 	 the user to try again later.
	 	 If login information is invalid, a message will prompt the
	 	 user that the information provided is not authorized.
	 	 If successful login, this activity ends and returns control
	 	 to the Main Interface of Carmen Travel Mobile Application.
	 */
	private Handler handler = new Handler() 
	{
        public void handleMessage(Message msg) 
        {
        	dialog.dismiss();

        	if (!connected)
        	{
        		Toast.makeText(getApplicationContext(), 
						"Unable to connect!\nPlease try again " +
						"later", 1).show();
        	}
        	
        	else if (connected && !isValidAccount)
			{
				Toast.makeText(getApplicationContext(), 
						"Authorization Failed!\nPlease check your " +
						"username and password\n", 1).show();
			}
			
			// Return to Main
			if (connected && isValidAccount)
			{
				Intent resultIntent = new Intent();
				resultIntent.putExtra(getString(R.string.username), username);
				resultIntent.putExtra(getString(R.string.password), password);
				setResult(Activity.RESULT_OK, resultIntent);
				dialog.dismiss(); // added precaution before returning to caller
				finish();
			}
        }
	};
	
	
	/**
	   Connects to Carmen (Drupal) WebSite with the user login information
	   @return true if connected, otherwise false
	 */
	private boolean connectToDrupal()
	{
		try 
		{
			SharedPreferences settings = getSharedPreferences(
					getString(R.string.app_name), 0);
			String apiKey = settings.getString("apiKey", "");
			String serviceDomain = settings.getString("serviceDomain", "");
			String serviceURL = settings.getString("serviceURL", "");
			DrupalXmlRpcService carmenService = 
				new DrupalXmlRpcService(serviceDomain, apiKey, serviceURL);
			connected = carmenService.connect(); 
			isValidAccount = carmenService.login(username, password);
			carmenService.logout();
			return connected;
		}
		catch (Exception e)
		{
			Log.d("Login Failed", e.getMessage());
			return false;
		}
	}
	
	
	/**
	   Pre-XMLRPC Service call check. A username and password must be provided.
	   @return true if both username and password have been filled, otherwise false.
	 */
	private boolean isValidLogin()
	{
		username = usernameEditText.getText().toString();
		password = passwordEditText.getText().toString();
		
		if (username.length() == ZERO && password.length() != ZERO)
			Toast.makeText(getApplicationContext(), 
					"Enter a username", 1).show();
		
		else if (username.length() != ZERO && password.length() == ZERO)
			Toast.makeText(getApplicationContext(), 
					"Enter a password!", 1).show();
		
		else if (username.length() == ZERO && password.length() == ZERO)
		{
			Toast.makeText(getApplicationContext(), 
					"Enter a username and password!", 1).show();
		}
		
		else if (username.length() > ZERO && password.length() > ZERO)
			return true;
		
		return false; 
	}
}
